package org.hrqing.chess.util;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.stream.IntStream;

/**
 * @author Hrqing
 */
public class ImageUtils {

    public static Image loadImage(String path) {
        try {
            return ImageIO.read(new ClassPathResource(path).getInputStream());
        } catch (IOException e) {
            throw new RuntimeException("image load error" + path, e);
        }
    }

    public static Image loadReverseImage(String path) {
        try {
            BufferedImage image = ImageIO.read(new ClassPathResource(path).getInputStream());
            int w = image.getWidth();
            int h = image.getHeight();
            BufferedImage dest = new BufferedImage(w, h, image.getType());

            IntStream.range(0,  h).parallel().forEach(y ->
                    IntStream.range(0,  w).forEach(x -> {
                        // 计算反向坐标
                        int mirrorX = w - 1 - x;
                        int mirrorY = h - 1 - y;
                        dest.setRGB(mirrorX,  mirrorY, image.getRGB(x,  y));
                    })
            );
            return dest;
        } catch (IOException e) {
            throw new RuntimeException("image load error" + path, e);
        }
    }
}
